/*DONE* Table [dbo].[<CompanyName>$LSC Information Subcode$5ecfc871-5d82-43f1-9c54-59685e82318d]  1/1  Script Date: 17.11.2022 - GKO ******/
/*Add prestaging table for all companies in LSInsight$Companies table*/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

DECLARE @CreateTable as VARCHAR(MAX)
DECLARE @Company as VARCHAR(100)
DECLARE @CompanyCounter as INT
DECLARE @i as INT

SET @i = 0
SET @CompanyCounter = (SELECT MAX([Company]) FROM LSInsight$Companies)

WHILE @i <= @CompanyCounter 
BEGIN
SET @Company = (SELECT LSInsight$Companies.[CompanyPrefix] from dbo.LSInsight$Companies WHERE [Company] = @i)

IF @Company IS NOT NULL
BEGIN

DECLARE @DropTable as VARCHAR(MAX)
SET @DropTable = 'DROP TABLE IF EXISTS [dbo].['+@Company+'$LSC Information Subcode$5ecfc871-5d82-43f1-9c54-59685e82318d]'
EXEC(@DropTable)

SET @CreateTable = 'CREATE TABLE [dbo].['+@Company+'$LSC Information Subcode$5ecfc871-5d82-43f1-9c54-59685e82318d](
	[timestamp] [timestamp] NOT NULL,
	[Code] [nvarchar](20) NOT NULL,
	[Subcode] [nvarchar](20) NOT NULL,
	[Description] [nvarchar](100) NOT NULL,
	[Primary Key] [nvarchar](31) NOT NULL,
	[Usage Category] [int] NOT NULL,
	[Trigger Function] [int] NOT NULL,
	[Trigger Code] [nvarchar](20) NOT NULL,
	[New Salesline] [tinyint] NOT NULL,
	[Variant Code] [nvarchar](10) NOT NULL,
	[Variant Needed] [tinyint] NOT NULL,
	[Qty_ Linked to Trigger Line] [tinyint] NOT NULL,
	[Price Type] [int] NOT NULL,
	[Price Handling] [int] NOT NULL,
	[Amount _Percent] [decimal](38, 20) NOT NULL,
	[Linked Infocode] [nvarchar](20) NOT NULL,
	[Unit of Measure] [nvarchar](10) NOT NULL,
	[Qty_ per Unit of Measure] [decimal](38, 20) NOT NULL,
	[Max_ Selection] [int] NOT NULL,
	[Serial_Lot No_ Needed] [tinyint] NOT NULL,
	[Min_ Selection] [int] NOT NULL,
	[Time Modifier Minutes] [decimal](38, 20) NOT NULL,
	[$systemId] [uniqueidentifier] NOT NULL,
	[$systemCreatedAt] [datetime] NOT NULL,
	[$systemCreatedBy] [uniqueidentifier] NOT NULL,
	[$systemModifiedAt] [datetime] NOT NULL,
	[$systemModifiedBy] [uniqueidentifier] NOT NULL,
 CONSTRAINT ['+@Company+'$LSC Information Subcode$5ecfc871-5d82-43f1-9c54-59685e82318d$Key1] PRIMARY KEY CLUSTERED 
(
	[Code] ASC,
	[Subcode] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY],
 CONSTRAINT ['+@Company+'$LSC Information Subcode$5ecfc871-5d82-43f1-9c54-59685e82318d$$systemId] UNIQUE NONCLUSTERED 
(
	[$systemId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]'

EXEC(@CreateTable)

END
SET @i = @i+1
END